<template>
	<div class="app-container">
		<el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
			<el-form-item label="企业名称" prop="companyName">
				<el-input v-model="queryParams.companyName" placeholder="请输入企业名称" clearable style="width: 200px"
					@keyup.enter="handleQuery" />
			</el-form-item>
			<el-form-item label="法人姓名" prop="legalPerson">
				<el-input v-model="queryParams.legalPerson" placeholder="请输入法人姓名" clearable style="width: 200px"
					@keyup.enter="handleQuery" />
			</el-form-item>
			<el-form-item label="签名状态" prop="signature">
				<el-select v-model="queryParams.signature" placeholder="请选择签名状态" clearable style="width: 200px">
					<el-option v-for="item in signatureStatusList" :key="item.value" :label="item.label"
						:value="item.value"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="节点" prop="nodes">
				<el-select v-model="queryParams.nodes" placeholder="请选择节点" clearable style="width: 200px">
					<el-option v-for="item in nodeList" :key="item.value" :label="item.label"
						:value="item.value"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="录入人" prop="createBy">
				<el-input v-model="queryParams.createBy" placeholder="请输入录入人" clearable style="width: 200px"
					@keyup.enter="handleQuery" />
			</el-form-item>
			<el-form-item label="额度冻结" prop="limitFreeze">
				<el-select v-model="queryParams.limitFreeze" placeholder="请选择额度冻结" clearable style="width: 200px"
					@keyup.enter="handleQuery">
					<el-option :value="-1" label="否" />
					<el-option :value="1" label="是" />
				</el-select>
			</el-form-item>
			<el-form-item v-if="isAdmin" label="所属战区">
        <el-select
          v-model="deptId"
          placeholder="请选择"
          clearable
          @change="getTeamTree"
          style="width: 168px"
        >
          <el-option
            v-for="item in deptOptions"
            :key="item.deptId"
            :label="item.deptName"
            :value="item.deptId"
          />
        </el-select>
      </el-form-item>
			<el-form-item v-if="isAdmin" label="所属团队">
        <el-select
          v-model="teamId"
          placeholder="请选择"
          clearable
          style="width: 168px"
        >
          <el-option
            v-for="item in teamOptions"
            :key="item.deptId"
            :label="item.deptName"
            :value="item.deptId"
          />
        </el-select>
      </el-form-item>
			<el-form-item>
				<el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
				<el-button icon="Refresh" @click="resetQuery">重置</el-button>
				<el-button icon="Plus" @click="handleQrCode">生成二维码</el-button>
				<div ref="qrCodeRef" style="display: none"></div>
			</el-form-item>
		</el-form>

		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button type="primary" plain icon="Plus" @click="handleAdd">新增
				</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate">修改
				</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除
				</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button
					type="warning"
					plain
					icon="Download"
					@click="handleExport"
					v-hasPermi="['company:export']"
				>
					导出
				</el-button>
			</el-col>
			<right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
		</el-row>

		<el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
			<el-table-column type="selection" width="55" align="center" />
			<el-table-column label="序号" align="center" prop="id" width="100" />
			<el-table-column label="企业名称" align="center" prop="companyName" width="240" />
			<el-table-column label="法人姓名" align="center" prop="legalPerson" width="100" />
			<el-table-column label="统一社会信用代码" align="center" prop="companyNo" width="200" />
			<el-table-column label="银行卡号" align="center" prop="bankNo" width="200" />
			<el-table-column label="开户行" align="center" prop="bankName" width="240" />
			<el-table-column label="银行预留手机号码" align="center" prop="bankPhone" width="140" />
			<el-table-column label="金额（万元）" align="center" prop="quotaAmount" width="130" />
			<el-table-column label="已提额度（万元）" align="center" prop="usedAmount" width="140" />

			<!-- <el-table-column label="年化利率" align="center" prop="moneyRate" width="80">
				<template #default="scope">
					{{ scope.row.moneyRate ? `${scope.row.moneyRate}%` : '-' }}
				</template>
</el-table-column> -->
			<el-table-column label="额度冻结" align="center" prop="limitFreeze" width="80">
				<template #default="scope">
					<el-tag v-if="scope.row.limitFreeze == -1" type="warning">否</el-tag>
					<el-tag v-if="scope.row.limitFreeze == 1" type="success">是</el-tag>
				</template>
			</el-table-column>
			<el-table-column label="节点" align="center" prop="nodes" width="120">
				<template #default="scope">
					<div v-if="scope.row.nodes === 1">未签约节点</div>
					<div v-if="scope.row.nodes === 2">已签约节点</div>
				</template>
			</el-table-column>
			<el-table-column label="下载类型" align="center" prop="downloadType" width="100">
				<template #default="scope">
					<div v-if="scope.row.downloadType === 1">二维码</div>
					<div v-if="scope.row.downloadType === 2">公众号</div>
					<div v-if="scope.row.downloadType === 3">下载app</div>
				</template>
			</el-table-column>
			<el-table-column label="下载内容提示" align="center" prop="downloadContent" width="120" show-overflow-tooltip />
			<el-table-column label="签名状态" align="center" prop="signature" width="80">
				<template #default="scope">
					<el-tag v-if="scope.row.signature == -1" type="warning">未签名</el-tag>
					<el-tag v-if="scope.row.signature == 1" type="success">已签名</el-tag>
				</template>
			</el-table-column>
			<el-table-column label="驳回原因" align="center" prop="rejectionReason" width="100" show-overflow-tooltip />
			<el-table-column label="驳回提示" align="center" prop="rejectionTip" width="100" show-overflow-tooltip />
			<el-table-column label="收款方名称" align="center" prop="payeeName" width="140" show-overflow-tooltip />
			<el-table-column label="合同模版" align="center" prop="contractModel" width="100" show-overflow-tooltip>
				<template #default="scope">
					<el-link v-if="scope.row.contractModel" type="primary" :href="scope.row.contractModel"
						target="_blank">合同模板</el-link>
				</template>
			</el-table-column>

			<el-table-column label="已签名的合同" align="center" prop="contractResult" width="120">
				<template #default="scope">
					<el-link v-if="scope.row.contractResult" type="primary" :href="scope.row.contractResult"
						target="_blank">已签签名合同</el-link>
				</template>
			</el-table-column>
			<el-table-column label="驳回处暂停" align="center" prop="rejectionPause" width="100">
				<template #default="scope">
					<el-tag v-if="scope.row.rejectionPause == -1" type="warning">否</el-tag>
					<el-tag v-if="scope.row.rejectionPause == 1" type="success">是</el-tag>
				</template>
			</el-table-column>
			<el-table-column label="创建者" align="center" prop="createBy" width="100" />
			<el-table-column label="创建时间" align="center" prop="createTime" width="100">
				<template #default="scope">
					<span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
				</template>
			</el-table-column>
			<el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="150">
				<template #default="scope">
					<el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改
					</el-button>
					<el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除
					</el-button>
				</template>
			</el-table-column>
		</el-table>

		<pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
			v-model:limit="queryParams.pageSize" @pagination="getList" />

		<!-- 添加或修改企业测额信息对话框 -->
		<el-dialog :title="title" v-model="open" width="830px" append-to-body>
			<el-form ref="formRef" :model="form" :rules="rules" label-width="150px">
				<el-row>
					<el-col :span="12">
						<el-form-item label="企业名称" prop="companyName">
							<el-input v-model="form.companyName" placeholder="请输入企业名称" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="法人姓名" prop="legalPerson">
							<el-input v-model="form.legalPerson" placeholder="请输入法人姓名" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="统一社会信用代码" prop="companyNo">
							<el-input v-model="form.companyNo" placeholder="请输入统一社会信用代码" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="银行卡号" prop="bankNo">
							<el-input v-model="form.bankNo" placeholder="请输入银行卡号" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="开户行" prop="bankName">
							<el-input v-model="form.bankName" placeholder="请输入开户行" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="银行预留手机号码" prop="bankPhone">
							<el-input v-model="form.bankPhone" placeholder="请输入银行预留手机号码" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="金额（万元）" prop="quotaAmount">
							<el-input-number step="0.01" :controls="false" v-model="form.quotaAmount"
								placeholder="请输入金额" style="width: 100%" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="已提额度（万元）" prop="usedAmount">
							<el-input-number step="0.01" :controls="false" v-model="form.usedAmount" placeholder="请输入金额"
								style="width: 100%" />
						</el-form-item>
					</el-col>
					<!-- <el-col :span="12">
						<el-form-item label="年化利率（%）" prop="moneyRate">
							<el-input-number step="0.01" :controls="false" v-model="form.moneyRate"
								placeholder="请输入年化利率" style="width: 100%" />
						</el-form-item>
					</el-col> -->
					<el-col :span="12">
						<el-form-item label="额度冻结" prop="limitFreeze">
							<el-select v-model="form.limitFreeze" placeholder="请选择额度冻结" style="width: 100%;">
								<el-option :value="-1" label="否" />
								<el-option :value="1" label="是" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="节点" prop="nodes">
							<el-select v-model="form.nodes" style="width: 100%;">
								<el-option label="未签约节点" :value="1"></el-option>
								<el-option label="已签约节点" :value="2"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="驳回处暂停" prop="rejectionPause">
							<el-select v-model="form.rejectionPause" style="width: 100%;">
								<el-option label="否" :value="-1"></el-option>
								<el-option label="是" :value="1"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="下载类型" prop="downloadType">
							<el-select v-model="form.downloadType" style="width: 100%;"
								@change="form.downloadContent = ''">
								<el-option :value="1" label="二维码"></el-option>
								<el-option :value="2" label="公众号"></el-option>
								<el-option :value="3" label="下载app"></el-option>
							</el-select>

						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="24">
						<el-form-item label="下载内容提示" prop="downloadContent">
							<template v-if="form.downloadType == 1">
								<FileUpload v-model="form.downloadContent" :limit="1" :fileType="['png', 'jpg', 'jpeg']"
									autoUpload />
							</template>
							<template v-else>
								<el-input v-model="form.downloadContent"></el-input>
							</template>

						</el-form-item>
					</el-col>
				</el-row>

				<el-row>
					<el-col :span="24">
						<el-form-item label="收款方名称" prop="payeeName">
							<el-input v-model="form.payeeName"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="合同模版" prop="contractModel">
							<FileUpload v-model="form.contractModel" :limit="1" :fileType="['pdf']" autoUpload />
						</el-form-item>
					</el-col>

					<el-col :span="24">
						<el-form-item label="驳回原因" prop="rejectionReason">
							<el-input type="textarea" v-model="form.rejectionReason" :rows="4" maxlength="1000"
								show-word-limit></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="驳回提示" prop="rejectionTip">
							<el-input v-model="form.rejectionTip" type="textarea" :rows="4" maxlength="200"
								show-word-limit></el-input>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="submitForm">确 定</el-button>
					<el-button @click="cancel">取 消</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<script setup>
import * as api from '@/api/quota/companySetting';
import { ElMessage, ElMessageBox } from 'element-plus';
import QRCode from 'qrcodejs2-fix';
import { getCurrentInstance, h, reactive, ref, toRefs } from 'vue';
import useConfig from '../hooks/useConfig'
import FileUpload from '@/components/FileUpload/index.vue'
import { fromPairs } from 'lodash';
import { listDept } from '@/api/system/dept'
import useUserStore from '@/store/modules/user'

const { proxy } = getCurrentInstance();

const userStore = useUserStore()

const isAdmin = computed(() => {
  return userStore.roles.includes('admin') || userStore.roles.includes('manager')
})

const deptId = ref(null)
const deptOptions = ref([])
function getDeptTree() {
  listDept({ deptName: '战区' }).then(response => {
    deptOptions.value = response.data
  })
}

const teamId = ref(null)
const teamOptions = ref([])
function getTeamTree() {
	teamId.value = null
  teamOptions.value = []

  if (!deptId.value) return

  listDept({ parentId: deptId.value }).then(response => {
    teamOptions.value = response.data
  })
}

if (userStore.roles.includes('admin') || userStore.roles.includes('manager')) {
  getDeptTree()
}

const {
	nodeList,
	signatureStatusList
} = useConfig()

const dataList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref('');
const qrCodeRef = ref();

const data = reactive({
	form: {},
	queryParams: {
		pageNum: 1,
		pageSize: 10,
		companyName: undefined,
		legalPerson: undefined,
		signature: undefined,
		nodes: undefined,
		createBy: undefined,
		limitFreeze: undefined
	},
	rules: {
		companyName: [{ required: true, message: '企业名称不能为空', trigger: 'blur' }],
		legalPerson: [{ required: true, message: '法人姓名不能为空', trigger: 'blur' }],
		quotaAmount: [{ required: true, message: '金额不能为空', trigger: 'change' }],
		nodes: [{ required: true, message: '节点不能为空', trigger: 'change' }],
		rejectionPause: [{ required: true, message: '驳回处暂停不能为空', trigger: 'change' }],
		// moneyRate: [{ required: true, message: '年化利率不能为空', trigger: 'blur' }]
	}
});

const { queryParams, form, rules } = toRefs(data);

/** 查询企业测额信息列表 */
function getList() {
	loading.value = true;
	api.list(queryParams.value).then(response => {
		dataList.value = response.rows;
		total.value = response.total;
		loading.value = false;
	});
}

/** 取消按钮 */
function cancel() {
	open.value = false;
	reset();
}

/** 表单重置 */
function reset() {
	form.value = {
		companyName: undefined,
		quotaAmount: undefined
	};
	proxy.resetForm('formRef');
}

/** 搜索按钮操作 */
function handleQuery() {
	queryParams.value.pageNum = 1;
	queryParams.value.deptId = teamId.value || deptId.value
	getList();
}

/** 重置按钮操作 */
function resetQuery() {
	proxy.resetForm('queryRef');
	deptId.value = null
	teamId.value = null
	handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
	ids.value = selection.map(item => item.id);
	single.value = selection.length !== 1;
	multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
	reset();
	open.value = true;
	title.value = '添加企业测额信息';
}

/**修改按钮操作 */
function handleUpdate(row) {
	reset();
	const id = row.id || ids.value;
	api.get(id).then(response => {
		form.value = response.data;
		open.value = true;
		title.value = '修改企业测额信息';
	});
}

/** 提交按钮 */
function submitForm() {
	proxy.$refs['formRef'].validate(valid => {
		if (valid) {
			if (form.value.id !== undefined) {
				api.update(form.value).then(response => {
					proxy.$modal.msgSuccess('修改成功');
					open.value = false;
					getList();
				});
			} else {
				api.add(form.value).then(response => {
					proxy.$modal.msgSuccess('新增成功');
					open.value = false;
					getList();
				});
			}
		}
	});
}

/** 删除按钮操作 */
function handleDelete(row) {
	const idList = row.id || ids.value;
	proxy.$modal.confirm('是否确认删除企业测额信息编号为"' + idList + '"的数据项？').then(function () {
		return api.remove(idList);
	}).then(() => {
		getList();
		proxy.$modal.msgSuccess('删除成功');
	}).catch(() => { });
}

async function handleQrCode() {
	qrCodeRef.value.innerHTML = '';
	const { data } = await api.getQrCodeId();
	const url = `${location.origin}/quota/h5/index.html?id=${data}`;

	new QRCode(qrCodeRef.value, {
		text: url,
		width: 128,
		height: 128,
		colorDark: '#000000',
		colorLight: '#ffffff',
		correctLevel: QRCode.CorrectLevel.H
	});

	const canvas = qrCodeRef.value.querySelector('canvas');
	// 将 Canvas 转换为 Data URL
	const dataURL = canvas.toDataURL();

	ElMessageBox({
		title: '测额二维码',
		showCancelButton: true,
		cancelButtonText: '复制二维码',
		confirmButtonText: '复制链接',
		message: h('p', {
			style: 'display: flex; align-items: center;'
		}, [
			h('img', { src: dataURL }),
			h('span', { style: 'margin-left: 10px;' }, url)
		])
	}).then(res => {
		// 复制url到剪切板
		navigator.clipboard.writeText(url).then(() => {
			ElMessage({
				message: '链接已复制',
				type: 'success'
			});
		}).catch(() => {
			console.error('链接复制失败');
		});
	}).catch(() => {
		// 创建一个 Blob 对象
		const blob = dataURLToBlob(dataURL);
		navigator.clipboard
			.write([new ClipboardItem({ 'image/png': blob })])
			.then(() => {
				ElMessage({
					message: '二维码已复制',
					type: 'success'
				});
			})
			.catch(() => {
				console.error('二维码复制失败');
			});
	});
}

function dataURLToBlob(dataURL) {
	const arr = dataURL.split(',');
	const mime = arr[0].match(/:(.*?);/)[1];
	const bstr = atob(arr[1]);
	let n = bstr.length;
	const u8arr = new Uint8Array(n);
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n);
	}
	return new Blob([u8arr], { type: mime });
}

function handleExport() {
  proxy.download(
    'quota/setting/export',
    {
      ...queryParams.value,
			deptId: teamId.value || deptId.value
    },
    `企业_${new Date().getTime()}.xlsx`
  )
}

getList();
</script>

<style scoped lang="less">
.el-input-number {
	::v-deep(.el-input__inner) {
		text-align: left;
	}
}
</style>
